<template>
  <div>
    <!-- 上传资源对话框 -->
    <el-dialog
      title="上传资源"
      :visible.sync="dialogVisible"
      width="500px"
      custom-class="upload-dialog"
      @close="handleClose"
    >
      <el-form
        ref="uploadForm"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="80px"
      >
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="uploadForm.name" placeholder="请输入资源名称" />
        </el-form-item>

        <el-form-item label="资源分类" prop="category">
          <el-select v-model="uploadForm.category" placeholder="请选择分类">
            <el-option
              v-for="category in displayCategories"
              :key="category.id || category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>

        <!-- 调试信息 -->
        <div v-if="categories.length === 0" style="color: red; margin-bottom: 10px;">
          警告: 没有可用的分类数据
        </div>
        <div v-else style="color: green; margin-bottom: 10px;">
          已加载 {{ categories.length }} 个分类
        </div>

        <el-form-item label="资源类型" prop="type">
          <el-radio-group v-model="uploadForm.type">
            <el-radio :label="1">免费</el-radio>
            <el-radio :label="2">积分</el-radio>
            <el-radio :label="3">付费</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 当选择积分类型时显示积分设置 -->
        <el-form-item v-if="uploadForm.type === 2" label="积分" prop="points">
          <el-input-number 
            v-model="uploadForm.points" 
            :min="1" 
            :max="100" 
            :step="1"
            controls-position="right"
          />
          <span class="points-tip">建议10-20积分</span>
        </el-form-item>
        
        <!-- 当选择付费类型时显示价格设置 -->
        <el-form-item v-if="uploadForm.type === 3" label="价格" prop="price">
          <el-input-number 
            v-model="uploadForm.price" 
            :min="0.1" 
            :max="100" 
            :step="0.1"
            :precision="2"
            controls-position="right"
          />
          <span class="price-unit">元</span>
        </el-form-item>
        
        <el-form-item label="网盘地址" prop="panPath">
          <el-input v-model="uploadForm.panPath" placeholder="请输入网盘地址" />
        </el-form-item>

        <el-form-item label="提取码" prop="panCode">
          <el-input v-model="uploadForm.panCode" placeholder="请输入提取码" />
        </el-form-item>
        
        <el-form-item label="资源描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="uploadForm.description" 
            rows="3"
            placeholder="请简要描述资源内容，帮助他人了解资源"
          />
        </el-form-item>
      </el-form>
      
      <!-- 添加积分说明信息 -->
      <div class="points-info" v-if="uploadForm.type === 2">
        <i class="el-icon-info"></i>
        <span>积分说明：用户下载此资源将消耗对应积分。您上传的资源被下载时，可获得下载者所消耗积分的70%作为奖励。</span>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addResourceApi } from '@/api/resources';
export default {
  name: "AddResource",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    categories: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      uploading: false,
      uploadForm: {
        name: '',
        category: '',
        type: 1, // 1: 免费, 2: 积分, 3: 付费
        points: 10, // 默认10积分
        price: 1.0, // 默认1元
        panPath: '',
        panCode: '',
        description: ''
      },
      uploadRules: {
        name: [
          { required: true, message: '请输入资源名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择资源分类', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择资源类型', trigger: 'change' }
        ],
        points: [
          { required: true, message: '请设置所需积分', trigger: 'blur' },
          { type: 'number', min: 1, message: '积分不能小于1', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请设置价格', trigger: 'blur' },
          { type: 'number', min: 0.1, message: '价格不能小于0.1元', trigger: 'blur' }
        ],
        panPath: [
          { required: true, message: '请输入网盘地址', trigger: 'blur' }
        ],
        panCode: [
          { required: true, message: '请输入提取码', trigger: 'blur' }
        ],
        description: [
          { required: false, message: '请输入资源描述', trigger: 'blur' },
          { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
        ]
      },
      // 默认分类数据
      defaultCategories: [
        { id: 1, label: '前端开发', value: '1' },
        { id: 2, label: '后端开发', value: '2' },
        { id: 3, label: '数据库', value: '3' },
        { id: 4, label: '设计素材', value: '4' },
        { id: 5, label: '电子书籍', value: '5' },
        { id: 6, label: '其他', value: '6' }
      ]
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    },
    // 计算属性，确保始终有可用的分类数据
    displayCategories() {
      console.log('AddResource - 接收到的分类数据:', this.categories);
      
      // 如果传入的分类数据为空，使用默认分类
      if (!this.categories || this.categories.length === 0) {
        console.log('AddResource - 使用默认分类数据');
        return this.defaultCategories;
      }
      
      return this.categories;
    }
  },
  watch: {
    // 监听对话框可见性变化
    dialogVisible(val) {
      if (val) {
        console.log('资源上传对话框打开，分类数据:', this.categories);
      }
    },
    // 监听分类数据变化
    categories: {
      handler(newVal) {
        console.log('分类数据更新:', newVal);
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    console.log('资源上传组件挂载，分类数据:', this.categories);
  },
  methods: {
    /**
     * 关闭对话框
     */
    handleClose() {
      this.dialogVisible = false;
      this.$refs.uploadForm.resetFields();
    },
    /**
     * 提交上传
     */
    submitUpload() {
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          this.uploading = true;
          
          // 构造提交的资源数据
          const resourceData = {
            name: this.uploadForm.name,
            category: this.uploadForm.category,
            type: this.uploadForm.type,
            points: this.uploadForm.type === 2 ? this.uploadForm.points : 0,
            price: this.uploadForm.type === 3 ? this.uploadForm.price : 0,
            panPath: this.uploadForm.panPath,
            panCode: this.uploadForm.panCode,
            description: this.uploadForm.description || ''
          };
          
          addResourceApi(resourceData).then(res => {
            this.$message.success("资源上传成功，等待博主审核！");
            // 重置表单
            this.$refs.uploadForm.resetFields();
            this.handleClose();
          }).catch(err => {
            this.$message.error(err.message || "上传失败，请稍后重试");
          }).finally(() => {
            this.uploading = false;
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.points-tip, .price-unit {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

.points-info {
  background-color: #f0f9eb;
  padding: 8px 16px;
  border-radius: 4px;
  margin-bottom: 16px;
  font-size: 13px;
  color: #67c23a;
  display: flex;
  align-items: flex-start;
  
  i {
    margin-right: 8px;
    margin-top: 2px;
  }
}
</style>
